package view;

import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘柄华
 * Date: 2022-06-10
 * Time: 15:03
 */

@WebServlet("/reg")
public class UserRegServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");
        req.setCharacterEncoding("utf-8");
        // 1. 先从请求中读取出 用户名 密码 和确认密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String ensurePassword = req.getParameter("ensurePassword");
        if(!password.equals(ensurePassword)){
            String html = "<h3>注册失败 两次密码输入不一致</h3>";
            resp.getWriter().write(html);
            return;
        }
        if (username == null || "".equals(username) || password == null || "".equals(password) || ensurePassword == null || "".equals(ensurePassword)) {
            String html = "<h3>注册失败! 未输入用户名或者密码!</h3>";
            resp.getWriter().write(html);
            return;
        }
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if(user != null){
            String html = "<h3>注册失败! 该用户名已存在,请重新输入!</h3>";
            resp.getWriter().write(html);
            return;
        }
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        userDao.insert(newUser);


        resp.getWriter().write("<script>alert('注册成功'); window.location.href='login.html';</script>");

    }
}
